#!/usr/bin/env python3
"""
腺样体检测服务启动脚本
用于启动Flask模型检测服务，供NodeJS后端调用
"""

import os
import sys
import subprocess
import argparse
from pathlib import Path

# 获取当前脚本目录
SCRIPT_DIR = Path(__file__).parent
FLASK_APP_DIR = SCRIPT_DIR / "flask_app"

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 7):
        print("❌ 错误: 需要Python 3.7或更高版本")
        print(f"   当前版本: {sys.version}")
        sys.exit(1)
    print(f"✅ Python版本检查通过: {sys.version}")

def check_virtual_env():
    """检查虚拟环境"""
    venv_dir = SCRIPT_DIR / "venv"
    if not venv_dir.exists():
        print("❌ 虚拟环境不存在，正在创建...")
        try:
            subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True)
            print("✅ 虚拟环境创建成功")
        except subprocess.CalledProcessError as e:
            print(f"❌ 虚拟环境创建失败: {e}")
            sys.exit(1)
    else:
        print("✅ 虚拟环境已存在")

def install_dependencies():
    """安装Python依赖"""
    requirements = [
        "torch>=1.9.0",
        "torchvision>=0.10.0",
        "opencv-python>=4.5.0",
        "pillow>=8.0.0",
        "flask>=2.0.0",
        "flask-cors>=3.0.10",
        "numpy>=1.21.0"
    ]

    # 检查是否在虚拟环境中
    if sys.prefix == sys.base_prefix:
        print("⚠️  警告: 未在虚拟环境中，建议先激活虚拟环境")
        print(f"   激活命令: {SCRIPT_DIR}\\venv\\Scripts\\activate")
    else:
        print("✅ 已在虚拟环境中")

    # 检查关键依赖
    try:
        import torch
        import cv2
        import flask
        import flask_cors
        print("✅ 关键依赖检查通过")
    except ImportError as e:
        print(f"❌ 缺少依赖: {e}")
        print("正在安装依赖...")
        try:
            subprocess.run([sys.executable, "-m", "pip", "install"] + requirements, check=True)
            print("✅ 依赖安装完成")
        except subprocess.CalledProcessError as e:
            print(f"❌ 依赖安装失败: {e}")
            sys.exit(1)

def check_model_file():
    """检查模型文件"""
    model_path = SCRIPT_DIR / "saved_models" / "best_model" / "best_model_fold4.pth"
    if not model_path.exists():
        print(f"❌ 模型文件不存在: {model_path}")
        print("   请确保模型文件位于 saved_models/best_model/best_model_fold4.pth")
        sys.exit(1)
    print(f"✅ 模型文件检查通过: {model_path}")

def start_flask_service(host='127.0.0.1', port=8001, debug=False):
    """启动Flask服务"""
    print(f"\n🚀 启动腺样体检测服务...")
    print(f"   服务地址: http://{host}:{port}")
    print(f"   调试模式: {'开启' if debug else '关闭'}")
    print(f"   API接口: http://{host}:{port}/predict")
    print(f"\n按 Ctrl+C 停止服务\n")

    # 设置环境变量
    env = os.environ.copy()
    env['PYTHONPATH'] = str(SCRIPT_DIR)
    env['FLASK_APP'] = 'app.py'

    try:
        # 启动Flask应用
        subprocess.run([
            sys.executable, "-m", "flask", "run",
            "--host", host,
            "--port", str(port),
            "--" + ("debug" if debug else "no-debug")
        ],
        cwd=FLASK_APP_DIR,
        env=env
        )
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 服务启动失败: {e}")
        sys.exit(1)

def main():
    parser = argparse.ArgumentParser(description="腺样体检测服务启动器")
    parser.add_argument("--host", default="127.0.0.1", help="服务主机地址 (默认: 127.0.0.1)")
    parser.add_argument("--port", type=int, default=8001, help="服务端口 (默认: 8001)")
    parser.add_argument("--debug", action="store_true", help="启用调试模式")
    parser.add_argument("--skip-checks", action="store_true", help="跳过环境检查")

    args = parser.parse_args()

    print("=" * 50)
    print("🏥 腺样体检测服务启动器")
    print("=" * 50)

    if not args.skip_checks:
        # 环境检查
        check_python_version()
        check_virtual_env()
        install_dependencies()
        check_model_file()
        print("\n✅ 所有检查通过，准备启动服务")
    else:
        print("⚠️  跳过环境检查，直接启动服务")

    # 启动服务
    start_flask_service(args.host, args.port, args.debug)

if __name__ == "__main__":
    main()
